import { useActionState } from "react";

// 跟useFormStatus区别就是actions中自己控制是否返回

async function addToCart(prevState: any, queryData: any) {
  console.log(prevState, queryData);

  const itemID = queryData.get("itemID");
  if (itemID === "1") {
    return {
      sussess: true,
      message: "已成功加入购物车：JavaScript：权威指南",
    };
  } else {
    // 人为添加延迟以使等待更明显。
    await new Promise((resolve) => {
      setTimeout(resolve, 2000);
    });
    return {
      sussess: false,
      message: "加入失败。。。。。。。。。。。。。。。：JavaScript：优点荟萃",
    };
  }
}

function AddToCartForm({ itemID, itemTitle }: any) {
  const [message, formAction, isPending] = useActionState(addToCart, {
    sussess: false,
    message: "",
  });
  return (
    <form action={formAction}>
      <h2>{itemTitle}</h2>
      <input type="hidden" name="itemID" value={itemID} />
      <button type="submit">加入购物车</button>
      {isPending ? "加载中……" : message.message}
    </form>
  );
}

function USEACTIONState() {
  return (
    <>
      <AddToCartForm itemID="1" itemTitle="JavaScript：权威指南" />
      <AddToCartForm itemID="2" itemTitle="JavaScript：优点荟萃" />
    </>
  );
}

export default USEACTIONState;
